# -*- coding: utf-8 -*-
import asyncio
import websockets
import datetime

# 存储所有连接的客户端和连接时间
clients = {}

async def handle_client(websocket, path):
    # 当有新客户端连接时将调用此函数
    clients[websocket.remote_address] = {"connection_time": datetime.datetime.now(), "websocket": websocket}

    print(f"来自ip为{websocket.remote_address} 路径为{path}的新连接，连接时间：{clients[websocket.remote_address]['connection_time']}")

    try:
        while True:
            # 等待来自客户端的消息
            message = await websocket.recv()
            print(f"来自 {websocket.remote_address} 的消息：{message}")

            # # 向所有客户端发送响应
            # response = f"服务器接收到：{message}"
            # for client, _ in clients.items():
            #     await client.send(response)
            # print(f"发送响应：{response}")

            # 向所有客户端发送响应
            response = f"服务器接收到来自{websocket.remote_address}的信息：{message}"
            for client_info in clients.values():
                await client_info['websocket'].send(response)
            print(f"发送响应：{response}")

    except websockets.exceptions.ConnectionClosed:
        print(f"ip为{websocket.remote_address} 路径为{path}的连接已关闭，断开时间：{clients[websocket.remote_address]['connection_time']}")
        # 当连接关闭时，将客户端从字典中移除
        del clients[websocket.remote_address]


async def main():
    # 创建一个 WebSocket 服务器
    server = await websockets.serve(handle_client, "172.21.29.40", 8765)

    print("WebSocket 服务器已启动")

    # 保持服务器运行
    await server.wait_closed()

if __name__ == "__main__":
    asyncio.run(main())